package com.commodity.servlet;

import com.commodity.Service.OrderService;
import com.commodity.Service.orderServiceImp.OrderServiceImp;
import com.commodity.entity.Order;
import com.commodity.entity.OrderSearchBean;
import com.commodity.utils.BeanFactory;
import com.commodity.utils.FormatMatch;
import com.commodity.utils.PaginateInfo;
import com.commodity.utils.ServletUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

@WebServlet("/order/*")
public class OrderServlet extends HttpServlet {
    private final OrderService orderService = BeanFactory.getInstance(OrderServiceImp.class);
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String action = req.getPathInfo();
        String method = req.getMethod().toLowerCase();
        if ("/list".equals(action)){
            if ("get".equals(method)){
                System.out.println(req.getParameter("id"));
                req.setAttribute("id",req.getParameter("id"));
                req.getRequestDispatcher("/WEB-INF/jsp/order/list.jsp").forward(req,resp);
            }else {
                list(req,resp);
            }
        } else if ("/add".equals(action)) {
            if ("get".equals(method)){
                System.out.println(action+""+method);
                String error = (String) req.getSession().getAttribute("error");
                if (StringUtils.hasText(error)){
                    req.setAttribute("error",error);
                    req.getSession().removeAttribute("error");
                    Order order = (Order) req.getSession().getAttribute("order");
                    req.setAttribute("order",order);
                    req.getSession().removeAttribute("order");
                }
                req.getRequestDispatcher("/WEB-INF/jsp/order/add.jsp").forward(req,resp);
            }else{
                add(req,resp);
            }
        } else if ("/delete".equals(action)) {
            delete(req,resp);
        } else if ("/edit".equals(action)) {
            if ("get".equals(method)){
                System.out.println(action+""+method);
                String id = req.getParameter("id");
                if (StringUtils.hasText(id)){
                    Order order = orderService.findById(Integer.valueOf(id));
                    if (order==null){
                        req.setAttribute("error","订单信息不存在");
                    }else{
                        req.setAttribute("order",order);
                    }

                }else{
                    req.setAttribute("error","未指定修改的订单主键");
                }
                req.getRequestDispatcher("/WEB-INF/jsp/order/edit.jsp").forward(req,resp);
            }else{
                edit(req,resp);
            }
        }

    }




    private void list(HttpServletRequest req, HttpServletResponse resp) {
        String pageNo = req.getParameter("pageNo");
        String pageSize = req.getParameter("pageSize");
        String orderId = req.getParameter("orderId");
        String customerId = req.getParameter("customerId");
        String commodityId = req.getParameter("commodityId");
        String quantityFrom = req.getParameter("quantityFrom");
        String quantityTo = req.getParameter("quantityTo");
        String customerPhone = req.getParameter("customerPhone");
        String orderTimeFrom = req.getParameter("orderTimeFrom");
        String orderTimeTo = req.getParameter("orderTimeTo");
        String commodityIdFromCommodity = req.getParameter("id");
        int iPageNo = 1;
        int iPageSize = 10;
        if (StringUtils.hasText(pageNo)){
            iPageNo = Integer.valueOf(pageNo);
        }
        if (StringUtils.hasText(pageSize)){
            iPageSize = Integer.valueOf(pageSize);
        }
        PaginateInfo pi = new PaginateInfo(iPageNo,iPageSize);
        List<Order> orderList = null;
        if (commodityIdFromCommodity==""){

            OrderSearchBean osb = new OrderSearchBean();
            if (StringUtils.hasText(orderId)){
                osb.setOrderId(orderId);
            }
            if (StringUtils.hasText(customerId)){
                osb.setCustomerId(customerId);
            }
            if (StringUtils.hasText(commodityId)){
                osb.setCommodityId(commodityId);
            }
            if (StringUtils.hasText(quantityFrom)){
                osb.setQuantityFrom(Integer.valueOf(quantityFrom));
            }
            if (StringUtils.hasText(quantityTo)){
                osb.setQuantityTo(Integer.valueOf(quantityTo));
            }
            if (StringUtils.hasText(customerPhone)){
                osb.setCustomerPhone(customerPhone);
            }
            if (StringUtils.hasText(orderTimeFrom)){
                LocalDate localDateFrom = LocalDate.parse(orderTimeFrom, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                osb.setOrderTimeFrom(localDateFrom);
            }
            if (StringUtils.hasText(orderTimeTo)){
                LocalDate localDateTo = LocalDate.parse(orderTimeTo,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                osb.setOrderTimeTo(localDateTo);
            }

            orderList = orderService.findAll(osb,pi);
        }else {
            orderList = orderService.findByCommodityId(commodityIdFromCommodity,pi);
        }


        ServletUtils.renderJson(Map.of("orderList",orderList,"pi",pi),resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String orderId = req.getParameter("orderId");
        String customerId = req.getParameter("customerId");
        String commodityId = req.getParameter("commodityId");
        String quantity = req.getParameter("quantity");
        String customerPhone = req.getParameter("customerPhone");
        String orderTime = req.getParameter("orderTime");
        String description = req.getParameter("description");

        String error = null;
        HttpSession session = req.getSession();
        Order order = new Order();

        if (!StringUtils.hasText(orderId)){
            error = "订单编号不可为空";
        }
        order.setOrderId(orderId);
        if (!StringUtils.hasText(customerId)){
            if (error == null){
                error = "用户编号不可为空";
            }
        }
        order.setCustomerId(customerId);
        if (!StringUtils.hasText(commodityId)){
            if (error == null){
                error = "客户编号不可为空";
            }
        }
        order.setCommodityId(commodityId);
        if (!StringUtils.hasText(commodityId)){
            if (error == null){
                error = "商品编号不可为空";
            }
        }
        order.setCommodityId(commodityId);

        Integer quantity1 = null;
        if (quantity!=""){
            quantity1 = Integer.valueOf(quantity);
        }
        if (quantity1 == null){
            if (error == null){
                error = "数量不可为空";
            }
        }
        order.setQuantity(quantity1);
        if (!StringUtils.hasText(customerPhone)){
            if (error == null){
                error = "电话号不可为空";
            }
        }
        if (!FormatMatch.validatePhoneNumber(customerPhone)){
            if (error==null){
                error = "手机号格式不正确";
            }
        }
        order.setCustomerPhone(customerPhone);
        if (orderTime == ""){
            if (error == null){
                error = "下单时间不可为空";
            }
        }
        LocalDate localDate = LocalDate.parse(orderTime,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        order.setOrderTime(localDate);

        order.setDescription(description);
        if (error!=null){
            session.setAttribute("error",error);
            session.setAttribute("order",order);
            resp.sendRedirect(req.getContextPath()+"/order/add");
        }

        boolean success = orderService.add(order);

        if (success){
            resp.sendRedirect(req.getContextPath()+"/order/list");
        }else {
            session.setAttribute("error","添加失败,请稍后再试或联系管理员");
            session.setAttribute("order",order);
            resp.sendRedirect(req.getContextPath()+"/order/add");
        }
    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) {
        String[] ids = req.getParameterValues("ids");

        Integer[] intIds = Stream.of(ids).map(Integer::valueOf).toArray(Integer[]::new);
        int rows = orderService.deleteByIds(intIds);
        ServletUtils.renderJson(Map.of("success",true,"rows",rows),resp);
    }


    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");

        Order order = orderService.findById(Integer.valueOf(id));

        String error = null;
        HttpSession session = req.getSession();

        String orderId = req.getParameter("orderId");
        String customerId = req.getParameter("customerId");
        String commodityId = req.getParameter("commodityId");
        String quantity = req.getParameter("quantity");
        String customerPhone = req.getParameter("customerPhone");
        String orderTime = req.getParameter("orderTime");
        String description = req.getParameter("description");

        if (!StringUtils.hasText(orderId)){
            error = "订单编号不可为空";
        }
        order.setOrderId(orderId);
        if (!StringUtils.hasText(customerId)){
            if (error == null){
                error = "用户编号不可为空";
            }
        }
        order.setCustomerId(customerId);
        if (!StringUtils.hasText(commodityId)){
            if (error == null){
                error = "客户编号不可为空";
            }
        }
        order.setCommodityId(commodityId);
        if (!StringUtils.hasText(commodityId)){
            if (error == null){
                error = "商品编号不可为空";
            }
        }
        order.setCommodityId(commodityId);

        Integer quantity1 = null;
        if (quantity!=""){
            quantity1 = Integer.valueOf(quantity);
        }
        if (quantity1 == null){
            if (error == null){
                error = "数量不可为空";
            }
        }
        order.setQuantity(quantity1);
        if (!StringUtils.hasText(customerPhone)){
            if (error == null){
                error = "电话号不可为空";
            }
        }
        if (!FormatMatch.validatePhoneNumber(customerPhone)){
            if (error==null){
                error = "手机号格式不正确";
            }
        }
        order.setCustomerPhone(customerPhone);
        if (orderTime == ""){
            if (error == null){
                error = "下单时间不可为空";
            }
        }
        LocalDate localDate = LocalDate.parse(orderTime,DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        order.setOrderTime(localDate);

        order.setDescription(description);
        if (error!=null){
            session.setAttribute("error",error);
            session.setAttribute("order",order);
            resp.sendRedirect(req.getContextPath()+"/order/edit?id="+id);
            return;
        }
        boolean success = orderService.update(order);
        if (success){
            resp.sendRedirect(req.getContextPath()+"/order/list");
        }else{
            session.setAttribute("error","修改失败,请稍后再试或联系管理员");
            session.setAttribute("order",order);
            resp.sendRedirect(req.getContextPath()+"/order/edit");
            return;
        }
    }

}
